<?php
namespace app\sw\controller;

use app\api\controller\Base;
use app\sw\model\FileModel;


/**
 * Class Index
 * @package app\index\controller
 */
class WorkFile extends Base
{

    // 获取某种类型的文件下载列表
    public function getFileList(){
        $this->checkUserLogin();
        $fileList = $this->_query(new FileModel())->order('id desc')->equal('file_template_id', input())->page(false, false, false, 10);    
        return $this->returnSuccess($fileList, '获取成功');
    }


    // 按月分组获取最近6个月的文件数据
    public function getFileListByMonth(){
        $this->checkUserLogin();
        $fileModel = new FileModel();
        $map = [];
        $map[] = ['ym_timestamp', '>=', strtotime('-12 month', strtotime(date('Y-m-01')))];

        $where = [];

        if($this->checkIsAdmin() == false){
            $where[] = ['dept_id', 'in', [0, $this->user['dept_id']]];
        }

        // 获取最近12个月的文件数据
        $fileList = $fileModel->where($map)->order('ym_timestamp desc')->with([
            'sheets' => function($query) use($where){
            $query->with(['result_file', 'department'])->where($where);
        }])->select();

        // 对数据进行与月份遍历分组
        $fileList = $fileList->toArray();
        $result = [];
        foreach ($fileList as $item) {

            if(!isset($result[md5($item['ym_timestamp'])])){
                $result[md5($item['ym_timestamp'])] = [
                    'ym_timestamp' => $item['ym_timestamp'],
                    'ym_str' => $item['ym_str'],
                    'year' => $item['year'],
                    'month' => $item['month'],
                    'file' => [],
                ];
            }
            $result[md5($item['ym_timestamp'])]['file'][] = $item;
        }
        return $this->returnSuccess(array_values($result), '获取成功');
    }

}